package com.yungu.swift.admin.route.common;

import com.yungu.swift.admin.base.CurrentUser;
import com.yungu.swift.admin.consts.AdminErrorEnum;
import com.yungu.swift.admin.utils.UploadUtils;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.model.admin.AdminParam;
import com.yungu.swift.utils.ParamUtil;
import com.yungu.swift.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import static com.yungu.swift.admin.config.NacosListener.SYS_CONFIG;

/**
 * @author : cuixiuyin
 * @date : 2019/6/15
 */
@Slf4j
@RestController
@RequestMapping("/admin/v1/common")
@Api(value = "【通用服务】", tags = "上传接口")
public class UploadAdmin {

    @RequestMapping(value = "/image/upload", method = RequestMethod.POST)
    @ApiOperation(value = "图片上传接口", httpMethod = "POST")
    public ResponseData<String> imageUpload(
            @RequestPart("image") MultipartFile image,
            @RequestParam(required = false) String mobile,
            @CurrentUser AdminParam adminParam) {
        if (ParamUtil.isIllegal(image)) {
            return ResponseData.buildErrorResponse(AdminErrorEnum.PARAM_ERROR.getCode(), AdminErrorEnum.PARAM_ERROR.getMsg());
        }
        ResponseData<String> responseData = UploadUtils.uploadImage(image, adminParam.getAppid(),
                ParamUtil.isIllegal(mobile) ? "admin" : mobile, "admin");
        if (!responseData.isSuccess() || StringUtils.isEmpty(responseData.getData())) {
            return responseData;
        }
        return ResponseData.buildSuccessResponse(getMYPICFullImagesURL(responseData.getData()));
    }

    @RequestMapping(value = "/file/upload", method = RequestMethod.POST)
    @ApiOperation(value = "文件上传接口", httpMethod = "POST")
    public ResponseData<String> fileUpload(
            @RequestPart("file") MultipartFile file,
            @RequestParam(required = false) String mobile,
            @CurrentUser AdminParam adminParam) {
        if (ParamUtil.isIllegal(file)) {
            return ResponseData.buildErrorResponse(AdminErrorEnum.PARAM_ERROR.getCode(), AdminErrorEnum.PARAM_ERROR.getMsg());
        }
        ResponseData<String> responseData = UploadUtils.uploadFile(file, adminParam.getAppid(),
                ParamUtil.isIllegal(mobile) ? "admin" : mobile);
        if (!responseData.isSuccess() || StringUtils.isEmpty(responseData.getData())) {
            return responseData;
        }
        return ResponseData.buildSuccessResponse(getMYPICFullImagesURL(responseData.getData()));
    }

    private String getMYPICFullImagesURL(String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            return "";
        }
        StringBuffer ret = new StringBuffer();
        ret.append(SYS_CONFIG.getWebSite());
        ret.append(fileName);

        return ret.toString();
    }
}
